package leetcode51_60;

import org.junit.Test;

import java.util.*;

/**
 * @author shhjiang_001
 * @create 2020-06-19 13:46
 */

       /*
       给出一个无重叠的 ，按照区间起始端点排序的区间列表。
       在列表中插入一个新的区间，你需要确保列表中的区间仍然有序且不重叠（如果有必要的话，可以合并区间）。
       示例 1:
       输入: intervals = [[1,3],[6,9]], newInterval = [2,5]
       输出: [[1,5],[6,9]]
       */

public class Solution57 {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        int length = intervals.length;
        ArrayDeque<int[]> deque = new ArrayDeque<>();
        deque.add(new int[]{newInterval[0],newInterval[1]});
        for (int i = 0; i < length; i++) {
            int[] last = deque.getLast();
            if (intervals[i][1] < last[0]){
                int[] temp = deque.removeLast();
                deque.addLast(new int[]{intervals[i][0],intervals[i][1]});
                deque.addLast(temp);
            }else if (intervals[i][0] > last[1]){
                deque.addLast(new int[]{intervals[i][0],intervals[i][1]});
            }else {
                last[1] = Math.max(intervals[i][1],last[1]);
                last[0] = Math.min(intervals[i][0],last[0]);
            }
        }
        int[][] ints = deque.toArray(new int[0][]);

        return ints;
    }
    @Test
    public void test(){
        insert(new int[][]{{1,2},{3,5},{6,7},{8,10},{12,16}},new int[]{4,8});
        int[] ints = {1, 2, 3, 6, 4, 4, 7, 8};
        List<Integer> list = Arrays.asList(1, 2, 3, 6, 4, 4, 7, 8);
        int[] arr1 = list.stream().mapToInt(Integer::valueOf).toArray();
        List<Character> list1 = Arrays.asList('a', 'b');
        int[] ints2 = list1.stream().mapToInt(Integer::valueOf).toArray();
        Integer[] ints1 = list.toArray(new Integer[0]);

    }
}
